
let reactiveFn = []
let deps = null

let handler = () => ({
  get: (target, key, desriptor) => {
    // 当数据被读取时， 收集依赖
    console.log(key);
    if(deps) {
      reactiveFn.push(deps)
    }
    
    return Reflect.get(target, key, desriptor)
  },
  set: (target, value, key, desriptor) => {
    Reflect.set(target, value, key, desriptor)
    console.log(reactiveFn);
    reactiveFn.forEach(fn => fn())
  }
})

function walk(data, handler) {
  if(typeof data !== 'object' || data === null) return
  for(let key in data) {
    data[key] = walk(data[key], handler)
  }
  // proxy深层级属性不会触发setter函数，所以这里需要遍历
  return new Proxy(data, handler())
}

function observable(data) {
  return walk(data, handler)
}

function ancron(cb) {
  // 收集依赖
  deps = cb
  cb()
  // 防止不是视图的数据变化导致不必要的更新
  deps = null
}

let data = {
  a: {
    b: 12
  },
  count: 1
}

let store = observable(data)
console.log(store);

// 类似于vue中computed
ancron(() => {
  console.log('ancron');
})

// store.count = 2